package cn.iocoder.yudao.module.knowledge.service.tree.impl;

import cn.iocoder.yudao.module.knowledge.service.tree.KnowledgeTreeService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.iocoder.yudao.module.knowledge.controller.admin.tree.vo.*;
import cn.iocoder.yudao.module.knowledge.dal.dataobject.tree.KnowledgeTreeDO;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.knowledge.dal.mysql.tree.KnowledgeTreeMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.knowledge.enums.ErrorCodeConstants.*;

/**
 * 知识库结构树 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class KnowledgeTreeServiceImpl implements KnowledgeTreeService {

    @Resource
    private KnowledgeTreeMapper treeMapper;

    @Override
    public Long createTree(KnowledgeTreeSaveReqVO createReqVO) {
        // 校验上级节点id的有效性
        validateParentTree(null, createReqVO.getParentId());
        // 校验节点名称的唯一性
        validateTreeNodeNameUnique(null, createReqVO.getParentId(), createReqVO.getNodeName());

        // 插入
        KnowledgeTreeDO tree = BeanUtils.toBean(createReqVO, KnowledgeTreeDO.class);
        treeMapper.insert(tree);

        // 返回
        return tree.getId();
    }

    @Override
    public void updateTree(KnowledgeTreeSaveReqVO updateReqVO) {
        // 校验存在
        validateTreeExists(updateReqVO.getId());
        // 校验上级节点id的有效性
        validateParentTree(updateReqVO.getId(), updateReqVO.getParentId());
        // 校验节点名称的唯一性
        validateTreeNodeNameUnique(updateReqVO.getId(), updateReqVO.getParentId(), updateReqVO.getNodeName());

        // 更新
        KnowledgeTreeDO updateObj = BeanUtils.toBean(updateReqVO, KnowledgeTreeDO.class);
        treeMapper.updateById(updateObj);
    }

    @Override
    public void deleteTree(Long id) {
        // 校验存在
        validateTreeExists(id);
        // 校验是否有子知识库结构树
        if (treeMapper.selectCountByParentId(id) > 0) {
            throw exception(TREE_EXITS_CHILDREN);
        }
        // 删除
        treeMapper.deleteById(id);
    }


    private void validateTreeExists(Long id) {
        if (treeMapper.selectById(id) == null) {
            throw exception(TREE_NOT_EXISTS);
        }
    }

    private void validateParentTree(Long id, Long parentId) {
        if (parentId == null || KnowledgeTreeDO.PARENT_ID_ROOT.equals(parentId)) {
            return;
        }
        // 1. 不能设置自己为父知识库结构树
        if (Objects.equals(id, parentId)) {
            throw exception(TREE_PARENT_ERROR);
        }
        // 2. 父知识库结构树不存在
        KnowledgeTreeDO parentTree = treeMapper.selectById(parentId);
        if (parentTree == null) {
            throw exception(TREE_PARENT_NOT_EXITS);
        }
        // 3. 递归校验父知识库结构树，如果父知识库结构树是自己的子知识库结构树，则报错，避免形成环路
        if (id == null) { // id 为空，说明新增，不需要考虑环路
            return;
        }
        for (int i = 0; i < Short.MAX_VALUE; i++) {
            // 3.1 校验环路
            parentId = parentTree.getParentId();
            if (Objects.equals(id, parentId)) {
                throw exception(TREE_PARENT_IS_CHILD);
            }
            // 3.2 继续递归下一级父知识库结构树
            if (parentId == null || KnowledgeTreeDO.PARENT_ID_ROOT.equals(parentId)) {
                break;
            }
            parentTree = treeMapper.selectById(parentId);
            if (parentTree == null) {
                break;
            }
        }
    }

    private void validateTreeNodeNameUnique(Long id, Long parentId, String nodeName) {
        KnowledgeTreeDO tree = treeMapper.selectByParentIdAndNodeName(parentId, nodeName);
        if (tree == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的知识库结构树
        if (id == null) {
            throw exception(TREE_NODE_NAME_DUPLICATE);
        }
        if (!Objects.equals(tree.getId(), id)) {
            throw exception(TREE_NODE_NAME_DUPLICATE);
        }
    }

    @Override
    public KnowledgeTreeDO getTree(Long id) {
        return treeMapper.selectById(id);
    }

    @Override
    public List<KnowledgeTreeDO> getTreeList(KnowledgeTreeListReqVO listReqVO) {
        return treeMapper.selectList(listReqVO);
    }

}